#!/usr/bin/env python

# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Authentication related decorators for handlers."""

import logging
import urllib
import common
from google.appengine.api import memcache
from lib import http
from lib.loggable import loggable
import model

__author__ = 'Maciej Machulak'
__maintainer__ = 'Maciej Machulak'
__email__ = 'mmachulak@google.com'

__copyright__ = 'Copyright 2012, Google Inc.'
__license__ = 'Apache License 2.0'
__version__ = '0.2'
__status__ = 'Prototype'

_SESSION_ID = common.SESSION_ID


def _get_session_id(request):
  """Retrieve session id from the cookie of the HTTP request."""

  try:
    session_id = request.cookies[_SESSION_ID]
  except KeyError:
    session_id = None
  return session_id


def _get_session(session_id=None):
  """Retrieve session by id from memcache."""

  if session_id is None:
    return None

  # If session id present, then try to retrieve session from memcache
  session = memcache.get(session_id)
  if session is None:
    # If session not in memcache then try datastore
    logging.debug('session not found in memcache, trying datastore')
    session = model.Session.all().filter('id = ', session_id).get()

  return session


def login_required(registered=True):
  """Decorator for handlers - checks if call is from authenticated user."""

  def inner_login_required(handler):
    """Requires that a user is logged in to be able to execute a method."""

    @loggable('check_login')
    def check_login(self, *args):
      """Checks status of the call."""
      session_id = _get_session_id(self.request)

      logging.debug('session id: %s', session_id)

      if session_id is None:
        logging.debug('session id is none - redirecting to main page')
        self.redirect(
            '/?continue_to=' + urllib.quote_plus(self.request.url))
        return

      session = _get_session(session_id)

      logging.debug('session %s', session)

      if session is None:
        logging.debug(
            'session could not be retrieved from the database')
        self.response.headers.add_header(http.Header.set_cookie,
                                         _SESSION_ID + '=')
        logging.debug('deleting session cookie')
        self.redirect(
            '/?continue_to=' + urllib.quote_plus(self.request.url))
        return
      if session.user is None:
        logging.debug('session present but user not associated')
        if registered:
          raise AuthError('session found but user not present')
      else:
        logging.debug('user found and associated with an existing '
                      'user')
        logging.debug('user has been logged in successfully')
        self.user = session.user
      self.session = session
      handler(self, *args)

    return check_login

  return inner_login_required


def redirect_logged_user(location='/'):
  """Decorator that redirects the user if the HTTP call is authenticated."""

  def inner_redirect(handler):

    @loggable('redirect logged user')
    def check_user_status(self, *args):
      session_id = _get_session_id(self.request)

      if session_id:
        logging.debug('session id: %s', session_id)

        session = _get_session(session_id)

        if session:
          if session.user:
            logging.debug('session for user %s', session.user)
            self.session = session
            self.user = session.user
            self.redirect(location)
            return
        logging.debug('session could not be retrieved from the DB')
        self.response.headers.add_header(http.Header.set_cookie,
                                         _SESSION_ID + '=')
        logging.debug('deleting session cookie')
      handler(self, *args)

    return check_user_status

  return inner_redirect


class AuthError(Exception):
  """Raised when there is an error with the authentication process."""

  def __init__(self, msg):
    Exception.__init__(self)
    self.msg = msg

  def __str__(self):
    return repr(self.msg)
